﻿using System.Threading;
using Topshelf;
using Topshelf.Logging;

namespace Musketeer
{
    class MusketeerWorker : ServiceControl
    {
        private readonly LogWriter logger = HostLogger.Get<MusketeerWorker>();
        public static bool ShouldStop { get; private set; }
        private ManualResetEvent stopHandle;

        public bool Start(HostControl hostControl)
        {
            logger.Info("Starting Muskeeter...");

            stopHandle = new ManualResetEvent(false);

            ThreadPool.QueueUserWorkItem(new ServiceMonitor().Monitor, stopHandle);

            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            ShouldStop = true;
            logger.Info("Stopping Muskeeter...");
            // wait for all threads to finish
            stopHandle.WaitOne(ServiceMonitor.SleepIntervalInMilliSecs + 10);

            return true;
        }
    }

    class Program
    {
        static void Main()
        {
            HostFactory.Run(hc =>
            {
                hc.UseNLog();
                // service is constructed using its default constructor
                hc.Service<MusketeerWorker>();
                // sets service properties
                hc.SetServiceName(typeof(MusketeerWorker).Namespace);
                hc.SetDisplayName(typeof(MusketeerWorker).Namespace);
                hc.SetDescription("Muskeeter - one to monitor them all.");
            });
        }
    }
}
